package xyz.xiezc.spider.prase;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.setting.Setting;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import xyz.xiezc.ioc.annotation.Component;
import xyz.xiezc.ioc.annotation.Inject;
import xyz.xiezc.spider.entity.MzituImgBean;
import xyz.xiezc.spider.common.Request;
import xyz.xiezc.spider.common.Response;
import xyz.xiezc.spider.common.XBean;

import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author wb-xzc291800
 * @date 2019/04/18 17:47
 */
@Slf4j
@Component
public class PhotoHtmlParseImpl implements ParseResponse {
    @Getter
    @Setter
    @Inject
    Setting setting;

    @Override
    public XBean parse(XBean xBean)  {

        this.dealParsePhoto(xBean);
        return xBean;
    }

    /**
     * 下载图片的保存
     *
     * @param xBean
     * @return
     */
    private String dealParsePhoto(XBean xBean) {
        Request request = xBean.getRequest();
        String url = request.getUrl();

        if (url.endsWith(".jpg")||url.endsWith(".jpeg")||url.endsWith(".png")) {
            Response response = xBean.getResponse();
            byte[] bodyByte = response.getBodyByte();
            String path = URLUtil.getPath(url);
            String img = setting.getStr("data.dir");
            //目录不存在的时候创建目录
            FileUtil.mkdir(img);
            String fileName = img + path;
            if (!FileUtil.exist(fileName)) {
                FileUtil.writeBytes(bodyByte, fileName);
            }

            Map<String, Object> extra = request.getExtra();
            Object albumId = extra.get("albumId");

            MzituImgBean mzituImgBean = new MzituImgBean();
            mzituImgBean.setAlbumId((int)albumId);
            mzituImgBean.setFetchUrl(url);

            mzituImgBean.setShowTime(Objects.toString(extra.get("showTime"),""));
            mzituImgBean.setTitle(Objects.toString(extra.get("title"),""));
            mzituImgBean.setType(Objects.toString(extra.get("type"),""));
            //这里保存的只是相对路径
            if (path.startsWith("/")) {
                path = path.substring(1);
            }
            mzituImgBean.setPath(path);
            mzituImgBean.setSize(bodyByte.length);
            List<MzituImgBean> mzituImgBeans = CollUtil.newArrayList(mzituImgBean);
            xBean.setBean(mzituImgBeans);
            xBean.setStatus(3);
        }
        return url;
    }

}
